#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2020/10/16 8:59
# @Author  : Wang Feng
# @FileName: uiautomation_parser.py
# @Software: PyCharm
"""
解析自动化脚本工程
"""

import inspect
import os
import pydoc
import re
from app.utils.testscript_parser.testscript_parser_utils import uiautomation_package, uiautomation_full_name, md5, \
    parse_comments, get_code_config


def get_test_case_paths(project_path: str) -> list:
    """
    获取测试文件列表
    :param project_name: 测试工程
    :return: 测试文件绝对路径组成的list
    """
    test_case_paths = list()
    for maindir, subdir, file_name_list in os.walk(project_path):
        # print("1:", maindir) #当前主目录
        # print("2:", subdir) #当前主目录下的所有目录
        # print("3:", file_name_list)  #当前主目录下的所有文件
        for filename in file_name_list:
            # print(filename)
            test_case_file = re.search('^test_.*.py$', filename)
            if test_case_file:
                apath = os.path.join(maindir, filename)  # 合并成一个完整路径
                # print(apath)
                test_case_paths.append(apath)
    return test_case_paths


def get_test_case_objs(project_path: str) -> list:
    """
    获取测试用例对象
    :param project_path: 测试工程
    :return: 解析测试用例文件后生成的测试对象list
    """
    test_case_paths = get_test_case_paths(project_path)
    test_case_objs = list()
    for test_case_path in test_case_paths:
        test_case_obj = dict()
        relpath = os.path.relpath(test_case_path, project_path)
        package = uiautomation_package(relpath)
        # 导入测试文件列表
        try:
            arg = pydoc.importfile(test_case_path)
            # 获取注解
            comments = inspect.getcomments(arg)
            # 获取源码
            source_code = inspect.getsource(arg)
            for name, obj in inspect.getmembers(arg):
                # print('name：' + name)
                # print(dir(obj))
                if inspect.isclass(obj) and 'Test' in name:
                    # 获取类名
                    clazz = name
                    # 获取用例名称
                    test_case_id = list(filter(lambda test_case: test_case.startswith('test_'), dir(obj)))[0]
                    test_case_full_name = uiautomation_full_name(package, clazz, test_case_id)
                    # 获取用例文档
                    test_case_doc = obj.__doc__

            test_case_obj['test_case_id'] = test_case_id
            test_case_obj['test_case_full_name'] = test_case_full_name
            test_case_obj['test_case_pk'] = md5(test_case_full_name)
            test_case_obj['comments'] = comments
            test_case_obj.update(parse_comments(comments))
            test_case_obj['test_case_doc'] = test_case_doc
            test_case_obj['source_code'] = source_code
            test_case_obj.update(get_code_config(source_code))
            test_case_obj['test_case_path'] = test_case_path
            test_case_objs.append(test_case_obj)
        except Exception as e:
            print(e)
    return test_case_objs


if __name__ == '__main__':
    # objs = get_test_case_objs('D:\Program Files\PyCharm 2019.1.3\workspace\E2TC\军民融合app')
    objs = get_test_case_objs('D:\Program Files\PyCharm 2019.1.3\workspace\军民融合_web')
    print(objs)
    # a = get_test_case_paths1('D:\Program Files\PyCharm 2019.1.3\workspace\E2TC\军民融合app')
    # print(a)
    # def treeStructure(startpath):
    #
    #     for root, dirs, files in os.walk(startpath):
    #         level = root.replace(startpath, '').count(os.sep)
    #         indent = ' ' * 2 * (level)
    #         print('{}|'.format(indent[:]))
    #         print('{}+{}/'.format(indent, os.path.basename(root)))
    #         subindent = ' ' * 2 * (level + 1)
    #
    #         for f in files:
    #             print('{}| +--- {}'.format(subindent[:-2], f))
    #
    # treeStructure('D:\Program Files\PyCharm 2019.1.3\workspace\军民融合_web')
    # import os
    # import os.path
    #
    #
    # def dfs_showdir(path, depth):
    #     if depth == 0:
    #         print("root:[" + path + "]")
    #     # print("当前文件路径是{}，包含文件有{}。".format(path, os.listdir(path)))
    #
    #     for item in os.listdir(path):
    #         if item in ['.git', '.idea', '__pycache__']:
    #             continue
    #
    #         print("| " * depth + "+--" + item)
    #
    #         new_item = path + '/' + item
    #         if os.path.isdir(new_item):
    #             dfs_showdir(new_item, depth + 1)
    # dfs_showdir('D:\Program Files\PyCharm 2019.1.3\workspace\军民融合_web', 0)
